package cn.htu.javaSong.service.impl;

import cn.htu.javaSong.common.ResponseHelper;
import cn.htu.javaSong.common.ResponseModel;
import cn.htu.javaSong.entity.Huya;
import cn.htu.javaSong.mapper.HuyaMapper;
import cn.htu.javaSong.service.IHuyaService;
import cn.htu.javaSong.utils.StringUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dakai
 * @since 2024-11-06
 */
@Service
public class HuyaServiceImpl extends ServiceImpl<HuyaMapper, Huya> implements IHuyaService {

    @Value("${huyaPath}")
    private String huyaPath;

    @Value("${server.port}")
    private String imgUrl;

    @Resource
    private HuyaMapper huyaMapper;

    @Override
    public ResponseModel addHuyaImg(List<Huya> huyas) {
        for (Huya huya: huyas) {
            Integer count = huyaMapper.selectHy(huya.getFileName());
            if (count != 0) {
                System.out.println("第" + huya.getCot() + "个【" + huya.getFileName() + "】已存在，添加失败");
            } else {
                Huya hy = new Huya();
                hy.setId(StringUtil.createUUID());
                hy.setFileName(huya.getFileName());
                hy.setFileUrl(huya.getFileUrl());
                String imageName = StringUtil.toPinyin(huya.getFileName()) + ".png";
                hy.setFileAddName(imageName);
                hy.setAddTime(new Date());
                String imageUrl = huya.getFileUrl();
                File imageFile = new File(String.valueOf(Paths.get(huyaPath, imageName)));
                hy.setFilePath(String.valueOf(imageFile));
                try {
                    hy.setFileAddress("http://" + InetAddress.getLocalHost().getHostAddress() + ":" + imgUrl + "/huya/" + imageName);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                RestTemplate restTemplate = new RestTemplate();
                byte[] imageBytes = restTemplate.getForObject(imageUrl, byte[].class);
                try {
                    FileUtils.writeByteArrayToFile(imageFile, imageBytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                this.save(hy);
                System.out.println("第" + huya.getCot() + "个【" + huya.getFileName() + "】添加成功");
            }
        }
        return ResponseHelper.responseModel(200,"添加成功","成功");
    }
}
